/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-07-28 09:06:15
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-07-29 19:29:35
 * @FilePath: /hw/110/Consumer_Productor/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "Thread.hpp"
#include "BlockQueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
#include <ctime>

using namespace std;
using namespace ThreadModule;

int a = 10;
using blockqueue_t = BlockQueue<Task>;
void Consumer(blockqueue_t &bq)
{
    while (1)
    {
        // 1.从blockqueue取得任务
        Task t;
        // 2.处理任务
        sleep(2);
        bq.Pop(&t);
        t.Excute();
        cout << "Consumer consume data: " << t.ResultToString() << endl;
    }
}
void Productor(blockqueue_t &bq)
{
    srand(time(nullptr) ^ pthread_self());
    int cnt = 1;
    while (1)
    {
        // 1.获取任务
        int a = rand() % 10 + 1;
        usleep(1234);
        int b = rand() % 20 + 1;
        Task t(a, b);
        // 将任务放入blockqueue
        //  sleep(1);
        bq.Enqueue(t);
        cout << "Productor product data: " << t.DebugToString() << endl;
    }
}
void StartComm(std::vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq,
               func_t<blockqueue_t> func)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        threads->emplace_back(func, bq, name);
        threads->back().Start();
    }
}
void StartConsumer(vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
    StartComm(threads, num, bq, Consumer);
}
void StartProductor(vector<Thread<blockqueue_t>> *threads, int num, blockqueue_t &bq)
{
    StartComm(threads, num, bq, Productor);
}
void WaitThread(vector<Thread<blockqueue_t>> &threads)
{

    for (auto &thread : threads)
    {
        thread.Join();
    }
}
int main()
{
    blockqueue_t *bq = new blockqueue_t(5);
    vector<Thread<blockqueue_t>> threads;
    StartConsumer(&threads, 1, *bq);
    StartProductor(&threads, 1, *bq);
    WaitThread(threads);

    return 0;
}